package xcache

import (
	"encoding/json"
)

// store in cache raw value, should know how to read back.
// Good practice: cache like key/value struct, value use []byte type.
// Cache data format

// Cache define a basic cache.
type Cache interface {

  // Put key/value to cache, overide exists. never expires
	Put(key string, value any) error

  // Read back raw value
  // Get(key string, ptr any) error

  // Get key value from cache.
	GetString(key string) (string, error)
  GetBytes(key string)([]byte,error)

  // Del key in cache, if not exists in cache, not return error.
  // error can be: service not avliable.
	Del(key string) error
}

// PutToJSON put value store in json bytes.
func PutToJSON(c Cache, key string, v any) error{
  data, err:=json.Marshal(v)
  if err != nil {
    return err
  }
  return c.Put(key, data)
}

// GetFromJSON .
func GetFromJSON(c Cache, key string, ptr any) error{
  data,err:=c.GetBytes(key)
  if err!=nil{
    return err
  }
  return json.Unmarshal(data, ptr)
}
